package com.bigshen.algorithm.aLinearList.solution01ReverseLinkedList;
/**
 * Reverse a singly linked list.
 *
 * Example:
 *
 * Input: 1->2->3->4->5->NULL
 * Output: 5->4->3->2->1->NULL
 *
 * 来源：力扣（LeetCode）
 * 链接：https://leetcode-cn.com/problems/reverse-linked-list
 * 著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。
 *
 * 递归方式翻转
 */
public class Solution02 {

    public ListNode reverseList(ListNode head) {

        if (null == head || null == head.next) {
            return head;
        }
        ListNode next = head.next;
        ListNode reverse = head;
        reverse.next = null;
        return reverse(next, reverse);
    }

    public ListNode reverse(ListNode head, ListNode reverse) {

        if (null == head) {
            return reverse;
        }

        ListNode next = head.next;
        head.next = reverse;
        return reverse(next, head);
    }

    public static void main(String[] args) {

        ListNode head = new ListNode(1);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(3);
        ListNode node4 = new ListNode(4);
        ListNode node5 = new ListNode(5);

        head.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;

        ListNode reverse = new Solution02().reverseList(head);

        ListNode tmp = reverse;
        while (null != tmp) {
            System.out.println(tmp.val);
            tmp = tmp.next;
        }

    }

}
